﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BulletinModel;
using BulletinMvc.Lib;
using Webdiyer.WebControls.Mvc;
namespace BulletinMvc.Controllers
{
    public class FeedbackController : Controller
    {
        //
        // GET: /Feedback/
       private BulletinDBEntities db;
        private IFeedbackBL iblfeedback;
        public FeedbackController()
        {
            db=new BulletinDBEntities();
            iblfeedback = new FeedbackBL(this.ModelState);        
        }

        public ActionResult AverageStar_TotalCommentCount(string projectSN)
        {
            ViewData["otalCommentCount"] = iblfeedback.GetCommentCountByprojectSN(projectSN);
            ViewData["AverageStarValue"] = iblfeedback.GetAverageStarvalueByprojectSN(projectSN);
            return PartialView();
        }


        public ActionResult MakeComment(string projectSN, int BulletinYaMa ,int YeMa )
        {
            ViewData["BulletinYaMa"] = BulletinYaMa;
            ViewData["YeMa"] = YeMa;       
          bool starfeedback= (from a in db.Bulletins  join b in db.BulletinItems on a.ID equals b.BulletinID  where b.ProjectSN==projectSN select a.StarFeedbackEnabled).SingleOrDefault() ;
          if (starfeedback == false)
              ViewData["StarVisible"] = "none";
            else
              ViewData["StarVisible"] = "normal";

          bool Textfeedback = (from a in db.Bulletins join b in db.BulletinItems on a.ID equals b.BulletinID where b.ProjectSN == projectSN select a.TextFeedbackEnabled).SingleOrDefault();
          if (Textfeedback == false)
              ViewData["TextVisible"] = "none";
          else
              ViewData["TextVisible"] = "normal";
          if (starfeedback == false && Textfeedback == false) ViewData["ButtonVisible"] = "none";
            ViewData["projectSN"] = projectSN;
            return PartialView();
        }

        private void createCookie(string projectSN, string userIp)
        {
            string cookname = projectSN + userIp;
            HttpCookie cook = new HttpCookie(cookname);
            //var expDays =24 * 60 * 60;
            //var expDate = new DateTime();
            //expDate.AddSeconds(expDays);
            cook.Expires = DateTime.Now.AddDays(1);
            cook.Values["userIp"] = userIp;
            Response.Cookies.Add(cook);
        }
        private bool haveCookInfo(string projectSN, string userIp)
        {
            string cookname = projectSN + userIp;
            HttpCookie cook = Request.Cookies[cookname];
            if (cook==null)
            {
                return false;
            }
            return true;
        } 
        [HttpPost]
        public ActionResult MakeCommentSavedata( FormCollection  collection)
        {
 
            string projectSN = Request.Form["projectSN"].Trim();
            //string noneStarValue = Request.Form["noneStarValue"].Trim();
            //string jsStarValue = Request.Form["StarValue"].Trim();
            string UserIP = Request.UserHostAddress.ToString();
            if (Request.Form["TextValue"].ToString().Trim() != "" || Request.Form["StarValue"] != "" || Request.Form["noneStarValue"] != null)
            {
                if (haveCookInfo(projectSN, UserIP))
                {
                    ModelState.AddModelError("", "您已经评价过,不能重复评价!");
                        ViewData["projectSN"]=projectSN;
                        ViewData["BulletinYaMa"]=Request.Form["BulletinYaMa"];
                        ViewData["YeMa"]=Request.Form["YeMa"];
                      return View();
                }
                var TextValue = Request.Form["TextValue"].ToString().Trim();
                int StarValue;
                if (Request.Form["StarValue"] =="" && Request.Form["noneStarValue"]==null) StarValue = 0;
                else if (Request.Form["StarValue"].ToString()!="") StarValue = Convert.ToInt16(Request.Form["StarValue"].ToString());
                else {
                    StarValue = Convert.ToInt16(Request.Form["noneStarValue"].ToString());                                
                }
                iblfeedback.AddComment(projectSN, StarValue, TextValue);
                createCookie(projectSN, UserIP);
                //    ModelState.AddModelError("", "评价成功！");      int YeMa, int BulletinYaMa     
                return RedirectToAction("giveComment", "BulletinItem", new { projectSN = projectSN, YeMa = Request.Form["YeMa"], BulletinYaMa = Request.Form["BulletinYaMa"] });
                //  return RedirectToAction("giveComment", "BulletinItem", new { projectSN = projectSN});
                //var script = String.Format("<script>alert('评论成功！');location.href='{0}'</script>", Url.Action("giveComment", "BulletinItem", new { projectSN = urlencode.UrlEncrypt(projectSN) }));
                //return Content(script, "text/html");
            }
            else {
                return RedirectToAction("giveComment", "BulletinItem", new { projectSN = projectSN, YeMa = Request.Form["YeMa"], BulletinYaMa = Request.Form["BulletinYaMa"] });

                //ModelState.AddModelError("", "请先评论！");
                //return PartialView("MakeComment");
                //var script = String.Format("<script>alert('请先评论！');location.href='{0}'</script>", Url.Action("giveComment", "BulletinItem", new { projectSN = urlencode.UrlEncrypt(projectSN) }));
                //return Content(script, "text/html");
                //ModelState.AddModelError("", "请先评论!");
                //return RedirectToAction("giveComment", "BulletinItem", new { projectSN = urlencode.UrlEncrypt(projectSN) });
            }
        }



//不在使用，合到上面一起
        [HttpPost]
        public ActionResult NonejsMakeCommentSavedata(FormCollection collection)
        {
            string UserIP = Request.UserHostAddress.ToString();
            string projectSN = Request.Form["projectSN"].Trim();
            if (Request.Form["TextValue"].ToString().Trim() != "" || Request.Form["StarValue"].ToString() != "")
            {
                if (haveCookInfo(projectSN, UserIP))
                {
                    ModelState.AddModelError("", "您已经评价过,不能重复评价!");
                    ViewData["projectSN"] = projectSN;
                    ViewData["BulletinYaMa"] = Request.Form["BulletinYaMa"];
                    ViewData["YeMa"] = Request.Form["YeMa"];
                    return View("MakeCommentSavedata");
                }
                var TextValue = Request.Form["TextValue"].ToString().Trim();
                int StarValue;
                if (Request.Form["StarValue"].ToString().Trim() == "") StarValue = 0;
                else StarValue = Convert.ToInt16(Request.Form["StarValue"].ToString().Trim());
                iblfeedback.AddComment(projectSN, StarValue, TextValue);
                createCookie(projectSN, UserIP);
                //    ModelState.AddModelError("", "评价成功！");      int YeMa, int BulletinYaMa     
                return RedirectToAction("giveComment", "BulletinItem", new { projectSN = projectSN, YeMa = Request.Form["YeMa"], BulletinYaMa = Request.Form["BulletinYaMa"] });
                //  return RedirectToAction("giveComment", "BulletinItem", new { projectSN = projectSN});
                //var script = String.Format("<script>alert('评论成功！');location.href='{0}'</script>", Url.Action("giveComment", "BulletinItem", new { projectSN = urlencode.UrlEncrypt(projectSN) }));
                //return Content(script, "text/html");
            }
            else
            {
                return RedirectToAction("giveComment", "BulletinItem", new { projectSN = projectSN, YeMa = Request.Form["YeMa"], BulletinYaMa = Request.Form["BulletinYaMa"] });

                //ModelState.AddModelError("", "请先评论！");
                //return PartialView("MakeComment");
                //var script = String.Format("<script>alert('请先评论！');location.href='{0}'</script>", Url.Action("giveComment", "BulletinItem", new { projectSN = urlencode.UrlEncrypt(projectSN) }));
                //return Content(script, "text/html");
                //ModelState.AddModelError("", "请先评论!");
                //return RedirectToAction("giveComment", "BulletinItem", new { projectSN = urlencode.UrlEncrypt(projectSN) });
            }
        }


        public ActionResult FeedBackList(string projectSN, int BulletinYaMa, int YeMa)
        {
            ViewData["BulletinYaMa"] = BulletinYaMa;
            ViewData["YeMa"] = YeMa;
            ViewData["projectSN"] = projectSN;  
            var feedbacklist = iblfeedback.GetFeedBackList(projectSN);
            return PartialView(feedbacklist);
        }
//前10条的删除，备用
        public ActionResult DeleteCommentByID(int ID,string projectSN, int BulletinYaMa, int YeMa)
        {
            ViewData["BulletinYaMa"] = BulletinYaMa;
            ViewData["YeMa"] = YeMa;
            ViewData["projectSN"] = projectSN;
            var feedbackbyid = iblfeedback.GetCommentByID(ID);
            return View(feedbackbyid);
        }
        [HttpPost, ActionName("DeleteCommentByID")]
        public ActionResult DeleteCommentByIDComfirm(int ID, string projectSN,int BulletinYaMa, int YeMa)
        {
            if( iblfeedback.DeleteCommentByID(ID))
                return RedirectToAction("giveComment", "BulletinItem", new { projectSN = projectSN, YeMa = Request.Form["YeMa"], BulletinYaMa = Request.Form["BulletinYaMa"] });
            else
            {
                ModelState.AddModelError("","删除出错！");
                var feedbackbyid = iblfeedback.GetCommentByID(ID);
                return View("DeleteCommentByID", feedbackbyid);
            }       

        } 
        //
        // POST: /Feedback/Create
//呈现所有评论的删除
        public ActionResult DeleteCommentByIDintotal(int ID, string projectSN, int BulletinYaMa, int YeMa)
        {
            ViewData["BulletinYaMa"] = BulletinYaMa;
            ViewData["YeMa"] = YeMa;
            ViewData["projectSN"] = projectSN;
            var feedbackbyid = iblfeedback.GetCommentByID(ID);
            return View(feedbackbyid);
        }
        [HttpPost, ActionName("DeleteCommentByIDintotal")]
        public ActionResult DeleteCommentByIDintotalComfirm(int ID, string projectSN, int BulletinYaMa, int YeMa)
        {
            if (iblfeedback.DeleteCommentByID(ID))
                return RedirectToAction("GetAllComment", new { projectSN = projectSN, BulletinYaMa = BulletinYaMa, YeMa = YeMa });
            else
            {
                ModelState.AddModelError("", "删除出错！");
                var feedbackbyid = iblfeedback.GetCommentByID(ID);
                return View("DeleteCommentByIDintotal", feedbackbyid);
            }

        } 


        //public ActionResult DeleteCommentByIDintotal(int ID, string projectSN, int BulletinYaMa, int YeMa)
        //{
        //    if (iblfeedback.DeleteCommentByID(ID))
        //        return RedirectToAction("GetAllComment", new { projectSN = projectSN, BulletinYaMa = BulletinYaMa, YeMa = YeMa });
        //    return null;        
        //}


        public ActionResult GetAllComment(string projectSN, int BulletinYaMa, int YeMa, int pagesize = 20, int id = 1)
        {
            ViewData["BulletinYaMa"] = BulletinYaMa;
            ViewData["YeMa"] = YeMa;
            ViewData["projectSN"] = projectSN;
            ViewData["bulletinmane"] = (from a in db.Bulletins join b in db.BulletinItems on a.ID equals b.BulletinID where b.ProjectSN==projectSN select a.Name).FirstOrDefault().ToString();
            ViewData["projectname"] = db.BulletinItems.Where(a=>a.ProjectSN==projectSN).Select(a=>a.ProjectTitle).FirstOrDefault();
            PagedList<Feedback> Allfeedback = iblfeedback.GetAllFeedBackList(projectSN).ToPagedList(id, pagesize);
            return View(Allfeedback);
        }


        [HttpPost]
        public ActionResult BatchDelete(FormCollection coll)
        {
            string ids = coll["ckSelect"];

            foreach (var item in ids.Split(','))//循环每一项Id
            {
                if (item != "false")//筛选掉自动生成的checkbox初始值
                {
                    var user = db.Feedbacks.Find(Convert.ToInt32(item));
                    db.Feedbacks.Remove(user);
                }

            }
            db.SaveChanges();
            return RedirectToAction("GetAllComment", new { projectSN = Request.Form["projectSN"], BulletinYaMa = Request.Form["BulletinYaMa"], YeMa = Request.Form["YeMa"] });
        }


        [HttpPost]
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        
        //
        // GET: /Feedback/Edit/5
 
        public ActionResult Edit(int id)
        {
            return View();
        }

        //
        // POST: /Feedback/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add update logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Feedback/Delete/5
 
        public ActionResult Delete(int id)
        {
            return View();
        }

        //
        // POST: /Feedback/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                // TODO: Add delete logic here
 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
